<template>
  <div>
    <div style="padding:10px;max-width:1000px;">
    <!-- 产品名称选择 -->
    <el-card>
      <span style="font-size:16px;margin-right:5px;font-weight:700;">产品名称</span>
      <el-select style="width:300px;margin-right:5px;" v-model="productId" ref="productSelector">
        <el-option v-for="p,i in productList" :value="p.id" :label="p.name" :key="i"></el-option>
      </el-select>
      <el-button type="primary" @click="querySuccessRate">查询</el-button>

      <span style="float:right;">
        <el-input style="width:200px;margin-right:5px;" v-model.trim="newProductName" placeholder="在此输入新产品的名称"></el-input>
        <el-input style="width:120px;margin-right:5px;" v-model="newProductFund" placeholder="产品初始资金"></el-input>
        <el-button type="success" icon="el-icon-plus" @click="createNewProduct">新增</el-button>
      </span>
    </el-card>
    <!-- 产品名称，策略数量等详情信息 -->
    <div style="margin:10px 10px; width:600px;">
      <el-row :gutter='8'>
        <el-col :span='3'><span>产品名称:</span></el-col>
        <el-col :span='4'><span class="product-value">{{ productDetailObj.name }}</span></el-col>
        <el-col :span='3'><span>初始资金:</span></el-col>
        <el-col :span='4'><span class="product-value">{{ productDetailObj.fund / 10000 > 1?(productDetailObj.fund / 10000).toFixed(0) + '万':productDetailObj.fund }}</span></el-col>
        <el-col :span='3'><span>累计收益:</span></el-col>
        <el-col :span='4'><span class="product-value">{{ productDetailObj.cum_profit / 10000 > 1?(productDetailObj.cum_profit / 10000).toFixed(2) + '万':productDetailObj.cum_profit }}</span></el-col>
      </el-row>
      <div style="height:10px;"></div>
      <el-row :gutter='8'>
        <el-col :span='3'><span>策略总数:</span></el-col>
        <el-col :span='4'><span class="product-value">{{ productDetailObj.total_count }}</span></el-col>
        <el-col :span='3'><span>正在运行:</span></el-col>
        <el-col :span='4'><span class="product-value">{{ productDetailObj.running_count }}</span></el-col>
      </el-row>
    </div>
    <!-- 产品成功率曲线 -->
    <el-card>
      <div style="width:100%;height:330px;">
        <vab-chart autoresize theme="vab-echarts-theme" :option="successRateChartOpt"></vab-chart>
      </div>
    </el-card>

    <!-- 产品详情和添加 -->
    <div>
      <el-tabs v-model="curTabName">
        <el-tab-pane label="策略添加" name="add">
          <div>
            <div style="font-size:22px;font-weight:700;margin-bottom:4px;">
              <span>按人员管理</span>
            </div>
            <div>
              <el-select filterable remote :remote-method="toQueryUserByName" style="width:300px;margin-right:10px;" v-model="userIdSelected" placeholder="输入名称查询人员">
                <el-option v-for="item,index in userList" :value="item.id" :label="item.admin_name" :key="index"></el-option>
              </el-select>
              <el-button type="primary" icon='el-icon-plus' @click="toManageStrategy('author_add')">添加</el-button>
              <el-button type="danger" icon='el-icon-delete' @click="toManageStrategy('author_remove')">移除</el-button>
            </div>
          </div>
          <br>
          <div>
            <div style="font-size:22px;font-weight:700;margin-bottom:4px;">
              <span>按时间管理</span>
            </div>
            <div>
              <el-date-picker v-model="timeRange" style="width:300px;margin-right:10px;" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
              <el-button type="primary" icon='el-icon-plus' @click="toManageStrategy('time_add')">添加</el-button>
              <el-button type="danger" icon='el-icon-delete' @click="toManageStrategy('time_remove')">移除</el-button>
            </div>
          </div>
          <br>
          <div>
            <div style="font-size:22px;font-weight:700;margin-bottom:4px;">
              <span>按人员和时间管理</span>
            </div>
            <div>
              <el-select filterable remote :remote-method="toQueryUserByName" style="width:300px;margin-right:10px;" v-model="userIdSelected2" placeholder="输入名称查询人员">
                <el-option v-for="item,index in userList" :value="item.id" :label="item.admin_name" :key="index"></el-option>
              </el-select>
              <el-date-picker v-model="timeRange2" style="width:300px;margin-right:10px;" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
              <el-button type="primary" icon='el-icon-plus' @click="toManageStrategy('author_time_add')">添加</el-button>
              <el-button type="danger" icon='el-icon-delete' @click="toManageStrategy('author_time_remove')">移除</el-button>
            </div>
          </div>
          <br>
          <div>
            <div style="font-size:22px;font-weight:700;margin-bottom:4px;">
              <span>按策略管理</span>
            </div>
            <!-- 策略列表 -->
            <div>
              <div v-for="item,index in strategyList" :key="index">
                <el-card style="margin:10px 2px;">
                  <div>
                    <span style="color:#e77800;line-height:28px;">{{ item.create_time }}</span>
                    <span style="float:right;"><el-button type="text" size="mini" @click="toManageStrategy('target_add', item)">添加</el-button></span>
                  </div>
                  <div style="line-height:26px;" :class="item.is_running?'running':''">{{ item.content }}</div>
                  <div><span style="font-size:12px;color:#999">{{ item.admin_name }}</span></div>
                </el-card>
              </div>
              <div>
                <el-pagination
                  background
                  layout="total,prev,pager,next"
                  :total="add_totalCount"
                  :current-page="add_page"
                  :page-size="add_pageSize"
                  @current-change="handleForAddPageChange">
                </el-pagination>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="策略详情" name="detail">
          <!-- 产品策略列表 -->
          <div>
            <div v-for="item,index in productStrategyList" :key="index">
              <el-card>
                <div>
                  <span style="color:#e77800;line-height:28px;">{{ item.create_time }}</span>
                  <span style="float:right;"><el-button type="text" style="color:#f34d37;" size="mini" @click="toManageStrategy('target_remove', item)">移除</el-button></span>
                </div>
                <div style="line-height:26px;" :class="item.is_running?'running':''">{{ item.content }}</div>
                <div><span style="font-size:12px;color:#999">{{ item.admin_name }}</span></div>
              </el-card>
            </div>
            <div>
              <el-pagination
                background
                layout="total,prev,pager,next"
                :total="p_totalCount"
                :current-page="p_page"
                :page-size="p_pageSize"
                @current-change="handProductPageChange">
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
  import VabChart from '@/plugins/echarts'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  import { queryUserByName } from '@/api/operations/user'
  import { getStrategyProduct, createStrategyProduct, productManageStrategy,
   productStrategy,productStrategySuccess
  } from '@/api/departmentWork/strategy'
  export default{
    components:{
      VabChart
    },
    data(){
      return {
        newProductName: '',
        newProductFund: 3000000,
        productDetailObj: {
          name: '',
          fund: null,
          current_cum_profut: null,
          running_count: null,
          total_count: null
        },
        productId: null,
        productList: [],
        curTabName: 'add',
        userList: [],
        userIdSelected: null,
        timeRange: [],
        userIdSelected2: null, // 按人员和时间添加的方式
        timeRange2: [],
        strategyList:[],  //待添加的策略列表
        add_page: 1,
        add_pageSize: 30,
        add_totalCount: 0,
        productStrategyList: [],  // 产品策略列表
        p_page: 1,
        p_pageSize: 30,
        p_totalCount: 0,
        successRateChartOpt: {
          title: {text: '策略产品累计成功率', x: 'center'},
          grid: {
            top: '15%',
            left: '2%',
            right: '4%',
            bottom: '0%',
            containLabel: true,
          },
          xAxis: [
            {
              type: 'category',
              /*boundaryGap: false,*/
              data: [],
              axisTick: {
                alignWithLabel: true,
              },
            },
          ],
          yAxis: [
            {
              type: 'value',
              name:'收益率%'
            }
          ],
          series: [
            {
              name: '收益率',
              type: 'line',
              symbol: 'none',
              lineStyle: {color: '#2277a2'},
              data: [],
            }
          ],
          tooltip: {trigger: 'axis', formatter: '{b0}<br /><span style=width:50px;display:inline-block>{a0}:</span><strong style=color:#2277a2>{c0}%</strong>'}
        },
      }
    },
    watch:{
      productId(n, o){
        if (!n) return
        this.querySuccessRate()  //查询成功率
        if (this.curTabName === 'add'){
          this.queryProductStrategy(0)  // 查询不在产品里面的策略
        }else if(this.curTabName === 'detail'){
          this.queryProductStrategy(1)  // 查询在产品里面的策略
        }
      },
      curTabName(n,o){
        if (this.curTabName === 'add'){
          this.queryProductStrategy(0)  // 查询不在产品里面的策略
        }else if(this.curTabName === 'detail'){
          this.queryProductStrategy(1)  // 查询在产品里面的策略
        }
      }
    },
    mounted() {
      this.queryProductList()
    },
    methods:{
      queryProductList(){
        getStrategyProduct().then(res => {
          this.productList = res.data
          if (this.productList.length>0){
            this.productId = this.productList[0].id
          }
        })
      },

      // 获取选中的产品
      getSelectedProduct(){
        let index = -1
        for (let i=0;i<this.productList.length;i++){
          if (this.productList[i].id === this.productId){
            index = i
            break
          }
        }
        return index
      },

      // 查询策略的图形曲线
      querySuccessRate(){
        if (!this.productId) return
        const index = this.getSelectedProduct()
        let productName = ''
        if (index > -1){
          productName = this.productList[index].name
        }
        productStrategySuccess({p: this.productId}).then(res => {

          const data = res.data
          console.log(res);
          this.productDetailObj = Object.assign(this.productDetailObj, data.product)
          // 设置图形配置
          const chartData = data.chart_data
          console.log(chartData);
          let chartOption = JSON.parse(JSON.stringify(this.successRateChartOpt))
          chartOption.title.text = productName + '累计收益率曲线图'
          if (res.code !== 200){
            chartOption.xAxis[0].data = []
            chartOption.series[0].data = []
          }else{
            console.log('设置数据');
            chartOption.xAxis[0].data = chartData.map(item => item.create_date)
            chartOption.series[0].data = chartData.map(item => (item.cum_profit_rate * 100).toFixed(2))
          }
          this.successRateChartOpt = chartOption
        }).catch(err => {
          let chartOption = JSON.parse(JSON.stringify(this.successRateChartOpt))
          chartOption.title.text = productName + '暂无曲线数据'
          chartOption.xAxis[0].data = []
          chartOption.series[0].data = []
          this.successRateChartOpt = chartOption
        })
      },

      // 不在产品内的策略页码变化
      handleForAddPageChange(page){
        this.add_page = page
        this.queryProductStrategy(0)
      },
      // 在产品内的策略页码变化
      handProductPageChange(page){
        this.p_page = page
        this.queryProductStrategy(1)
      },

      // 查询在/不在产品内的策略
      queryProductStrategy(isin){
        const param = {
          isin: isin,
          p: this.productId,
          page: isin===0?this.add_page:this.p_page,
          page_size: isin===0?this.add_pageSize:this.p_pageSize
        }
        productStrategy(param).then(res => {
          const data = res.data
          if (isin === 0){
            this.strategyList = data.data
            this.add_totalCount = data.total_count
            this.add_page = data.page
          }else if (isin === 1){
            this.productStrategyList = data.data
            this.p_totalCount = data.total_count
            this.p_page = data.page
          }else{ }
        })
      },

      // 通过名称查询用户
      toQueryUserByName(username){
        if (username.length < 1) return
        queryUserByName(username).then(res => {
          this.userList = res.data
        })
      },

      // 新增产品
      createNewProduct(){
        if (this.newProductName.length<1 || !this.newProductFund ||this.newProductFund<1){
          this.$baseMessage('请先输入策略产品和初始资金', 'error')
          return
        }
        const data = {
          name: this.newProductName,
          fund: this.newProductFund
        }
        createStrategyProduct(data).then(res => {
          if (res.code !== 201){
            this.$baseMessage(res.msg, 'error')
          }else{
            this.$baseMessage(res.msg, 'success')
            this.newProductName = ''
            this.queryProductList()
          }
        })
      },

      // 产品内新增策略
      toManageStrategy(action, item){
        const bodyData = {
          action: action,
          product_id: this.productId
        }
        if (!bodyData.product_id){
          this.$baseMessage('请选择一个产品再管理！', 'error')
          return
        }
        if (action === 'author_add' || action === 'author_remove'){
          // 按作者管理
          bodyData.creator_id = this.userIdSelected
          if (!bodyData.creator_id){
            this.$baseMessage('请选择策略作者！', 'error')
            return
          }
        }else if(action === 'time_add' || action === 'time_remove'){
          // 按时间添加
          bodyData.time_start = datetimeToStr(this.timeRange[0], true, '-')
          bodyData.time_end = datetimeToStr(this.timeRange[1], true, '-')
          if (!bodyData.time_start || !bodyData.time_end){
            this.$baseMessage('请选择时间区间！', 'error')
            return
          }
        }else if (action === 'author_time_add' || action === 'author_time_remove'){
          // 按时间作者添加
          bodyData.creator_id = this.userIdSelected2
          if (!bodyData.creator_id){
            this.$baseMessage('请选择策略作者！', 'error')
            return
          }
          bodyData.time_start = datetimeToStr(this.timeRange2[0], true, '-')
          bodyData.time_end = datetimeToStr(this.timeRange2[1], true, '-')
          if (!bodyData.time_start || !bodyData.time_end){
            this.$baseMessage('请选择时间区间！', 'error')
            return
          }
        }else if(action === 'target_add' || action === 'target_remove'){
          bodyData.strategy_id = item.id
        }else{return}
        productManageStrategy(bodyData).then(res => {
          this.$baseMessage(res.msg, 'success')
          this.querySuccessRate()
          if (this.curTabName === 'add'){
            this.queryProductStrategy(0)
          }else if(this.curTabName === 'detail'){
            this.queryProductStrategy(1)
          }
        })
      }
    }
  }
</script>

<style scoped>
  .product-value{
    color: #349cfc;
    font-weight:700;
  }
</style>
